package cn.sytton.taffecloud.common.servlet.handler;

import cn.sytton.taffecloud.common.base.exception.ApiException;
import cn.sytton.taffecloud.common.base.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.NestedServletException;

/**
 * 全局异常处理，捕获所有controller层service中抛出的异常
 *
 * @author skyrock
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public R<?> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.fail(e.getMessage());
    }

    //处理Feign调用的异常
    @ExceptionHandler(value = NestedServletException.class)
    public R<?> handleApiException(NestedServletException e) {
        log.error(e.getMessage(), e);
        return R.fail(getApiException(e).getMessage());
    }
    private Throwable getApiException(Throwable e) {
        if (e instanceof ApiException) {
            return e;
        } else {
            return getApiException(e.getCause());
        }
    }
}
